import React from 'react'
import { useRef } from 'react'
import { useSelector, useDispatch } from 'react-redux';
import { setIsShowModal, editTodo } from '../store/todoList';

function Modal() {
  console.log('Modal组件渲染了')
  const { isShowModal, modalTitle, modalContent, todoList} = useSelector((state) => state.todoList)
  const dispatch = useDispatch()
  // 查看modal
  const viewContent = (itemId) => {
    const {id, title, completed} = todoList.find(obj => obj.id === itemId) || {}
    return (
      <div className='innerContent'>
        <div>时间：{new Date(id).toLocaleString()}</div>
        <div>内容：{title}</div>
        <div>状态：{completed ? '完成' : '未完成'}</div>
        <button className='modalBtn' onClick={() => dispatch(setIsShowModal(false))}>确定</button>
      </div>
    )
  }
  // 编辑modal
  const textareaRef = useRef(null)
  const editContent = (itemId) => {
    const {id, title} = todoList.find(obj => obj.id === itemId) || {}
    return (
      <div className='innerContent'>
        <textarea key={id} className='textarea' defaultValue={title} ref={textareaRef}></textarea>
        <button className='modalBtn' onClick={() => changeTodoTitle(itemId)}>确定</button>
      </div>
    )
  }
  // 修改todo title
  const changeTodoTitle = (itemId) => {
    const val = textareaRef.current.value.trim()
    if (val) {
      dispatch(editTodo({id: itemId, title: val}))
      dispatch(setIsShowModal(false))
    }
  }
  return (
    <div className={`modal ${isShowModal && 'isShowModal'}`}>
      <div className="modalTitle">
        {modalTitle}
        <span className="close" onClick={() => dispatch(setIsShowModal(false))}>X</span>
      </div>
      <div className="modalContent">
        {modalContent.isViewContent ? viewContent(modalContent.id) : editContent(modalContent.id)}
      </div>
    </div>
  )
}

export default React.memo(Modal)